package cn.yijvyan.bos.web.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.yijvyan.bos.utils.MailUtils;
import cn.yijvyan.crm.domain.Customer;
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{
	
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Action(value="customer_sendSms")
	public String sendSms() throws IOException {
		String randomCode = RandomStringUtils.randomNumeric(4);
		System.out.println("运行到randomCode这一步");
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		System.out.println("生成手机验证码为：" + randomCode);
		
		final String msg = "尊敬的用户您好，本次获取的验证码为：" + randomCode + ",服务电话：4006184000";
		
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
			}
		});
		
		return NONE;
		
		
//		String result = SmsUtils.sendSmsByHTTP(model.getTelephone(), msg);
		/*String result = "0001/xxxx";
		if (result.startsWith("000")) {
			return NONE;
		} else {
			throw new RuntimeException("短信发送失败,信息码:"+result);
		}*/
	}
	
	
	private String checkcode;
	
	
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Action(value="customer_regist",results={
			@Result(name="success",type="redirect",location="signup-success.html"),
			@Result(name="input",type="redirect",location="signup.html")})
	public String regist() {
		String checkCodeSession = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if (checkCodeSession == null || !checkCodeSession.equals(checkcode)) {
			System.out.println("验证码错误 ...");
			return INPUT;
		} else {
			
			WebClient.create("http://localhost:9002/crm_management/services"
					+ "/customerService/customer").type(MediaType.APPLICATION_JSON).post(model);
			
			System.out.println("注册成功");
			
			
			String activecode = RandomStringUtils.randomNumeric(32);
			redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
			String content = "哟哟哟,年轻的顾客哟,请于24小时内,进行邮箱绑定,点击下面地址完成绑定哟:<br/><a href='"
					+MailUtils.activeUrl+"?telephone="+model.getTelephone()+"&activecode="
					+activecode+"'>易居岩慢递不送邮箱绑定地址</a>";
			MailUtils.sendMail("易居岩慢递不送", content, model.getEmail());
			
			return SUCCESS;
		}
	}
	
	
	private String activecode;


	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}
	
	@Action("customer_activeMail")
	public String activeMail() throws IOException{
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		
		if (activecodeRedis == null || !activecodeRedis.equals(activecode)) {
			
			System.out.println("0.telephone:"+model.getTelephone()+"1.activecode:"+activecode+"  2.activecodeRedis:"+activecodeRedis);
			
			ServletActionContext.getResponse().getWriter().println("激活码无效哟,请登录系统,重新绑定邮箱");
			
		} else {
			Customer customer = WebClient.create("http://localhost:9002/crm_management/services"
					+ "/customerService/customer/telephone/"+model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			
			System.out.println("由webservice查出来的customer是:"+customer);
			
			if (customer != null) {
				if (customer.getType() == null || customer.getType()!=1) {
					WebClient.create("http://localhost:9002/crm_management/services"
							+ "/customerService/customer/updatetype/"+model.getTelephone())
							.get();
					System.out.println("执行到要进行updatetype的这一步");
					ServletActionContext.getResponse().getWriter().println("邮箱绑定成功哟");
				} else {
					ServletActionContext.getResponse().getWriter().println("邮箱已绑定过,不需要再绑!");
				}
			}
			
			redisTemplate.delete(model.getTelephone());
		}
		return NONE;
	}
	
}
